package com.sinopec.android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;

import javax.crypto.EncryptedPrivateKeyInfo;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.sinopec.android.bean.AttDoc;
import com.sinopec.android.bean.DispathBasic;
import com.sinopec.android.bean.DocumentBean;
import com.sinopec.android.bean.ProcessIdea;
import com.sinopec.android.bean.ResultData;
import com.sinopec.android.bean.SubmitBusinessTripBean;
import com.sinopec.android.bean.Thing;
import com.sinopec.android.bean.ThreadCallBack;
import com.sinopec.android.constant.ConfigAttrs;
import com.sinopec.android.constant.Constants;
import com.sinopec.android.net.ThreadManger;
import com.sinopec.android.util.AsyncImageLoader;
import com.sinopec.android.util.AsyncImageLoader.ImageCallback;
import com.sinopec.android.util.ExitUtil;
import com.sinopec.android.util.LogUtil;
import com.sinopec.android.util.SharePreferencesUtil;
import com.sinopec.android.util.StringUtil;
import com.sinopec.android.util.ToastUtil;

/**
* @ClassName: DocumentDetailActivity
* @Description: TODO(查看公文详情)
* @author liuwei
* @date 2012-4-1 下午05:17:45
* 
*/
public class DocumentDetailActivity extends BaseActivity implements
		OnClickListener, ThreadCallBack {
	
	public static Dialog dialog;
	public  Context mContext = DocumentDetailActivity.this;
	
	
	/**整个文档视图**/
	ScrollView documet_scroll_layout = null;
	/**附件名称按钮**/
	LinearLayout document_path_layout = null;
	/**附件正文**/
	TextView document_zhengwen_textview = null;
	/**附件名称**/
	TextView document_name_textview = null;
	/**公文标题**/
	TextView document_title_textview = null;
	/**公文 编号**/
	TextView document_code_textview = null;
	/**来文日期 layout**/
	LinearLayout  document_laiwenriqi_layout = null;
	/***来文日期textview*/
	TextView document_laiwenriqi_textview = null;
	/**原文号 layout**/
	LinearLayout document_yuanwenhao_layout = null;
	/**原文号 textview**/
	TextView document_yuanwenhao_textview = null;
	/**收文号 layout**/
	LinearLayout document_shouwenhao_layout = null;
	/**收文号 textview**/
	TextView document_shouwenhao_textview = null;
	/**来文机关 layout**/
	LinearLayout document_laiwenjiguan_layout = null;
	/**来文机关 textview**/
	TextView document_laiwenjiguan_textview = null;
	/**来文标题 layout**/
	LinearLayout document_laiwenbiaoti_layout = null;
	/**来文标题 textview**/
	TextView document_laiwenbiaoti_textview = null;
	/**来文标题  加急**/
	TextView document_laiwenbiaoti_jiaji_textview = null;
	/**主管部门 layout **/
	LinearLayout process_idea_zhuguanbumen_layout = null;
	/**院领导阅示 layout**/
	LinearLayout process_idea_yuanlingdaoyueshi_layout = null;
	/**传阅人签字 layout**/
	LinearLayout process_idea_chuanyuerenqianzi_layout = null;
	/**主办部门layout**/
	LinearLayout process_idea_zhubanbumen_layout = null;
	/**备注 layout**/
	LinearLayout document_beizhu_layout = null;
	/**备注 textview**/
	TextView document_beizhu_textview = null;
	
	/**审批区域layout**/
	LinearLayout shenpi_layout = null;
	/***审批意见edittext**/
	EditText shenpiyijian_edittext = null;
	/**确定按钮**/
	Button  confirm_btn = null;
	
	LayoutInflater inflater;
	Thing thing;
	
	DocumentBean documentBean;
	ArrayList<AttDoc>  attDocList;
	ArrayList<ProcessIdea> processIdeaList;
	DispathBasic dispathBasic;
	
	//附件 
	String fileUrl=null;
	File file = null;
	String SDPath = Environment.getExternalStorageDirectory()+"/";
	String md5FileName = null;
	String md5FilePath = null;
	long count = 0;
	long total = 0;
	
	//是否已办公文
	boolean isYiBan;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.document_detail_view);
		thing = (Thing) getIntent().getSerializableExtra("thing");
		initView();
		//调接口
		sendToServer();
	}
	
	void initView(){
		inflater = getLayoutInflater();
		((TextView)findViewById(R.id.navi)).setText(thing.getTitle());
		documet_scroll_layout = (ScrollView) findViewById(R.id.document_scroll_layout);
		documet_scroll_layout.setVisibility(View.VISIBLE);//设置不可见
		document_path_layout = (LinearLayout) findViewById(R.id.document_path_layout);
		document_path_layout.setVisibility(View.GONE);//默认设置不可见

		document_title_textview = (TextView) findViewById(R.id.document_title_textview);
		document_code_textview = (TextView) findViewById(R.id.document_code_textview);
		document_laiwenriqi_layout = (LinearLayout) findViewById(R.id.document_laiwenriqi_layout);
		document_laiwenriqi_textview = (TextView)findViewById(R.id.document_laiwenriqi_textview);
		document_yuanwenhao_layout = (LinearLayout) findViewById(R.id.document_yuanwenhao_layout);
		document_yuanwenhao_textview = (TextView) findViewById(R.id.document_yuanwenhao_textview);
		document_shouwenhao_layout = (LinearLayout) findViewById(R.id.document_shouwenhao_layout);
		document_shouwenhao_textview = (TextView) findViewById(R.id.document_shouwenhao_textview);
		document_laiwenjiguan_layout = (LinearLayout) findViewById(R.id.document_laiwenjiguan_layout);
		document_laiwenjiguan_textview = (TextView) findViewById(R.id.document_laiwenjiguan_textview);
		document_laiwenbiaoti_layout = (LinearLayout) findViewById(R.id.document_laiwenbiaoti_layout);
		document_laiwenbiaoti_textview = (TextView) findViewById(R.id.document_laiwenbiaoti_textview);
		document_laiwenbiaoti_jiaji_textview = (TextView) findViewById(R.id.document_laiwenbiaoti_jiaji_textview);
		process_idea_zhuguanbumen_layout =  (LinearLayout) findViewById(R.id.process_idea_zhuguanbumen_layout);
		process_idea_yuanlingdaoyueshi_layout = (LinearLayout) findViewById(R.id.process_idea_yuanlingdaoyueshi_layout);
		process_idea_chuanyuerenqianzi_layout = (LinearLayout) findViewById(R.id.process_idea_chuanyuerenqianzi_layout);
		process_idea_zhubanbumen_layout = (LinearLayout) findViewById(R.id.process_idea_zhubanbumen_layout);
		document_beizhu_layout = (LinearLayout) findViewById(R.id.document_beizhu_layout);
		document_beizhu_textview = (TextView) findViewById(R.id.document_beizhu_textview);
		//审批区域
		shenpi_layout = (LinearLayout) findViewById(R.id.shenpi_layout);
		shenpiyijian_edittext = (EditText) findViewById(R.id.shenpiyijian_edittext);
		confirm_btn = (Button) findViewById(R.id.confirm_btn);
		confirm_btn.setOnClickListener(this);
		
		if(thing.isYiBan()){
			shenpi_layout.setVisibility(View.GONE);
		}
	}
	
	void sendToServer(){
		String reqUrl =ConfigAttrs.BASE_URL+"GetSuperiorDocument.ashx";
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("userName", SharePreferencesUtil.getLastLoginAccount(getApplicationContext(), ConfigAttrs.LAST_LOGIN_ACCOUNT));
		hashMap.put("passWord", SharePreferencesUtil.getLastLoginAccount(getApplicationContext(), ConfigAttrs.LAST_LOGIN_PWD));
		if(StringUtil.isEmpty(deviceId)){
			deviceId = "0000000000";
		}
		hashMap.put("deviceId", deviceId);
		hashMap.put("InsID", thing.getUrl());
		hashMap.put("bussinessID", thing.getBussinessID());
		hashMap.put("btnType", "1");

		ThreadManger.exeTask(this, ConfigAttrs.DOCUMENT_DETAIL_TASK_FLAG, hashMap, reqUrl);
	}
	@Override
	public void onCallbackFromThread(ResultData resultData) {
		// TODO Auto-generated method stub
		if(resultData!=null && resultData.getResultList()!=null){
		}else{
			Toast.makeText(this,R.string.get_fail, 0).show();
			return;
		}
		if(resultData.getResultList().get(0) instanceof String){
			Toast.makeText(this,resultData.getResultList().get(0).toString(), 0).show();
			return ;
		}
		ArrayList arrayList = resultData.getResultList();
		//公文结果
		if(arrayList.size()>0&&arrayList.get(0) instanceof DocumentBean){
			documet_scroll_layout.setVisibility(View.VISIBLE);//设置可见
			documentBean = (DocumentBean) arrayList.get(0);
			attDocList = documentBean.getAttDocList();
			processIdeaList = documentBean.getProcessIdeaList();
			//公文附件
			if(attDocList!=null&&attDocList.size()>0){
				document_path_layout.setVisibility(View.VISIBLE);
				
				
				for(int i=0;i<attDocList.size();i++){
					AttDoc attDoc = attDocList.get(i);
					if(attDoc!=null){
						View pathView = inflater.inflate(R.layout.document_detail_filepath_layout, null);
						pathView.setTag(attDoc.getAttFilePath());
						document_zhengwen_textview = (TextView) pathView.findViewById(R.id.document_zhengwen_textview);
						document_name_textview = (TextView) pathView.findViewById(R.id.document_name_textview);
						document_zhengwen_textview.setText("（"+attDoc.getTypeName()+"）");
						document_name_textview.setText(attDoc.getAttFieleName());
						document_path_layout.addView(pathView, new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.FILL_PARENT,
								LinearLayout.LayoutParams.WRAP_CONTENT));
						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.FILL_PARENT, 5);
						TextView textView = new TextView(this);
						textView.setLayoutParams(layoutParams);
						document_path_layout.addView(textView);
						pathView.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								fileUrl = v.getTag().toString();
								md5FileName = StringUtil.MD5(fileUrl)+fileUrl.substring(fileUrl.lastIndexOf("."));
								md5FilePath = SDPath+md5FileName;
//								ToastUtil.showToast(mContext,fileUrl );
//								
//								ToastUtil.showToast(mContext, md5FilePath);
								
								if(isExist(md5FilePath)){
									//直接
									openFile(new File(md5FilePath));
									return ;
								}else{
									//透明loading进度条
									dialog = new Dialog(mContext,R.style.NobackDialog);  
									dialog.setContentView(R.layout.dialog_loading);  
									TextView loadTip = (TextView) dialog.findViewById(R.id.loadTip);
									loadTip.setText(mContext.getResources().getString(R.string.loadingTip));
									
									dialog.show();
									
									dialog.setOnCancelListener(new OnCancelListener() {
										@Override
										public void onCancel(DialogInterface arg0) {
											LogUtil.printInfo("the dialog is cancel");
											//终止请求进程
										}
									});
									
									new Thread(new Runnable() {
										@Override
										public void run() {
							                HttpClient client = new DefaultHttpClient();  
							                HttpGet get = new HttpGet(fileUrl);  
							                HttpResponse response = null; 
							                FileOutputStream fileOutputStream = null;  
							                InputStream is=null;
							                try {  
							                	response = client.execute(get);
							                	if(response.getStatusLine().getStatusCode()!=200)
												throw new IOException("StatusCode!=200");
							                    HttpEntity entity = response.getEntity();  
							                    total = entity.getContentLength();
							                    is = entity.getContent(); 
							                    if (is != null) {  
							  
							                        file = new File(md5FilePath);  
							                        fileOutputStream = new FileOutputStream(file);  
							                          
							                        byte[] buf = new byte[1024];  
							                        int ch = -1;
							                        while ((ch = is.read(buf)) != -1) {
							                        	
							                        	count+=ch;
							                            fileOutputStream.write(buf, 0, ch);
							                        } 
							                        if(count==total)
							                        	mHandler.sendEmptyMessage(0);
							                        fileOutputStream.flush();
							                        if(fileOutputStream!=null)
							                        	fileOutputStream.close();
							                    } 
							                } catch (Exception e) {   
							                    e.printStackTrace();
							                    mHandler.sendEmptyMessage(1);
							                    
							                    if(file!=null&&file.exists())file.delete(); 
							        
							                } finally{
												try {
													if(is!=null){
														is.close();
													}
												} catch (IOException e1) {
													e1.printStackTrace();
													mHandler.sendEmptyMessage(1);
									                if(file!=null&&file.exists())file.delete(); 
												}
											}
										}
									}).start();
							 }
							}
						});
					}
				}
			}else{
				document_path_layout.setVisibility(View.GONE);
			}
			
			//公文表格数据
			dispathBasic = documentBean.getDispathBasic();
			document_laiwenriqi_textview.setText(dispathBasic.getRecData());
			document_yuanwenhao_textview.setText(dispathBasic.getRecNo());
			document_shouwenhao_textview.setText(dispathBasic.getDocNo());
			document_laiwenjiguan_textview.setText(dispathBasic.getRecDeport());
			document_laiwenbiaoti_textview.setText(dispathBasic.getRecTitle());
			if(StringUtil.isNotEmpty(dispathBasic.getTileState())){
				document_laiwenbiaoti_jiaji_textview.setText("（加急）");
			}
			document_beizhu_textview.setText(dispathBasic.getRemark());
			//主管部门领导意见  JobStep= 2
			//院领导阅示      JobStep= 4
			//传阅人签字     JobStep= 5
			//主办部门办理意见   JobStep= 6
			if(processIdeaList!=null &&processIdeaList.size()>0){
				for (int i = 0; i < processIdeaList.size(); i++) {
					ProcessIdea processIdea = processIdeaList.get(i);
					if(processIdea!=null &&processIdea.getJobStep()==2){
						View view = inflater.inflate(R.layout.process_idea_item_layout, null);
						TextView yjTextview = (TextView) view.findViewById(R.id.process_idea_yijian_textview);
						yjTextview.setText(processIdea.getSignComment());
						
						TextView timeTextview = (TextView) view.findViewById(R.id.process_idea_time_textview);
						timeTextview.setText(processIdea.getSignTime());
						
						TextView ldTextview = (TextView) view.findViewById(R.id.process_idea_lingdao_textview);
						if(StringUtil.isNotEmpty(processIdea.getSignUserName())){
							ldTextview.setText(processIdea.getSignUserName());
						}
						
						LinearLayout sign_in_layout = (LinearLayout) view.findViewById(R.id.sign_in_layout);
						if(StringUtil.isNotEmpty(processIdea.getSignUserPath())){
							sign_in_layout.setVisibility(View.VISIBLE);
						final	ImageView signImageView = (ImageView) view.findViewById(R.id.sign_in_image_view);
//							signImageView.setImageDrawable(getResources().getDrawable(Constants.getSignInImage(processIdea.getSignUserPath())));
							String url = processIdea.getSignUserPath();
							Bitmap bitmap = AsyncImageLoader.loadDrawable(url, new ImageCallback() {
								@Override
								public void imageLoaded(Bitmap imageDrawable, String imageUrl) {
//										ImageView imageView = (ImageView)listView.findViewWithTag(imageUrl);
										if(imageDrawable!=null ){
//											imageDrawable = ImageUtil.getRoundedCornerBitmap(imageUrl,imageDrawable, 10.0f);
//											imageView.setImageBitmap(imageDrawable);
											signImageView.setBackgroundDrawable(new BitmapDrawable(imageDrawable));
										}
								}
							});
							
							if(bitmap!=null){
								signImageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
							}
						}
						
						process_idea_zhuguanbumen_layout.addView(view);
						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.FILL_PARENT, 8);
						TextView textView = new TextView(this);
						textView.setLayoutParams(layoutParams);
						process_idea_zhuguanbumen_layout.addView(textView);
						
					}else if(processIdea!=null &&processIdea.getJobStep()==4){
						View view = inflater.inflate(R.layout.process_idea_item_layout, null);
						TextView yjTextview = (TextView) view.findViewById(R.id.process_idea_yijian_textview);
						yjTextview.setText(processIdea.getSignComment());
						
						TextView timeTextview = (TextView) view.findViewById(R.id.process_idea_time_textview);
						timeTextview.setText(processIdea.getSignTime());
						
						TextView ldTextview = (TextView) view.findViewById(R.id.process_idea_lingdao_textview);
						if(StringUtil.isNotEmpty(processIdea.getSignUserName())){
							ldTextview.setText(processIdea.getSignUserName());
						}
						
						LinearLayout sign_in_layout = (LinearLayout) view.findViewById(R.id.sign_in_layout);
						if(StringUtil.isNotEmpty(processIdea.getSignUserPath())){
							sign_in_layout.setVisibility(View.VISIBLE);
						final	ImageView signImageView = (ImageView) view.findViewById(R.id.sign_in_image_view);
							String url = processIdea.getSignUserPath();
							
							Bitmap bitmap = AsyncImageLoader.loadDrawable(url, new ImageCallback() {
								@Override
								public void imageLoaded(Bitmap imageDrawable, String imageUrl) {
//										ImageView imageView = (ImageView)listView.findViewWithTag(imageUrl);
										if(imageDrawable!=null ){
//											imageDrawable = ImageUtil.getRoundedCornerBitmap(imageUrl,imageDrawable, 10.0f);
//											imageView.setImageBitmap(imageDrawable);
											signImageView.setBackgroundDrawable(new BitmapDrawable(imageDrawable));
										}
								}
							});
						}
						
						process_idea_yuanlingdaoyueshi_layout.addView(view);
						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.FILL_PARENT, 8);
						TextView textView = new TextView(this);
						textView.setLayoutParams(layoutParams);
						process_idea_yuanlingdaoyueshi_layout.addView(textView);
						
					}else if(processIdea!=null &&processIdea.getJobStep()==5){
						View view = inflater.inflate(R.layout.process_idea_item_layout, null);
						TextView yjTextview = (TextView) view.findViewById(R.id.process_idea_yijian_textview);
						yjTextview.setText(processIdea.getSignComment());
						
						TextView timeTextview = (TextView) view.findViewById(R.id.process_idea_time_textview);
						timeTextview.setText(processIdea.getSignTime());
						
						TextView ldTextview = (TextView) view.findViewById(R.id.process_idea_lingdao_textview);
						if(StringUtil.isNotEmpty(processIdea.getSignUserName())){
							ldTextview.setText(processIdea.getSignUserName());
						}
						
						LinearLayout sign_in_layout = (LinearLayout) view.findViewById(R.id.sign_in_layout);
						if(StringUtil.isNotEmpty(processIdea.getSignUserPath())){
							sign_in_layout.setVisibility(View.VISIBLE);
							final	ImageView signImageView = (ImageView) view.findViewById(R.id.sign_in_image_view);
							String url = processIdea.getSignUserPath();
							
							Bitmap bitmap = AsyncImageLoader.loadDrawable(url, new ImageCallback() {
								@Override
								public void imageLoaded(Bitmap imageDrawable, String imageUrl) {
//										ImageView imageView = (ImageView)listView.findViewWithTag(imageUrl);
										if(imageDrawable!=null ){
//											imageDrawable = ImageUtil.getRoundedCornerBitmap(imageUrl,imageDrawable, 10.0f);
//											imageView.setImageBitmap(imageDrawable);
											signImageView.setBackgroundDrawable(new BitmapDrawable(imageDrawable));
										}
								}
							});
						}
						
						process_idea_chuanyuerenqianzi_layout.addView(view);
						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.FILL_PARENT, 8);
						TextView textView = new TextView(this);
						textView.setLayoutParams(layoutParams);
						process_idea_chuanyuerenqianzi_layout.addView(textView);
						
					}else if(processIdea!=null &&processIdea.getJobStep()==6){
						View view = inflater.inflate(R.layout.process_idea_item_layout, null);
						TextView yjTextview = (TextView) view.findViewById(R.id.process_idea_yijian_textview);
						yjTextview.setText(processIdea.getSignComment());
						
						TextView timeTextview = (TextView) view.findViewById(R.id.process_idea_time_textview);
						timeTextview.setText(processIdea.getSignTime());
						
						TextView ldTextview = (TextView) view.findViewById(R.id.process_idea_lingdao_textview);
						if(StringUtil.isNotEmpty(processIdea.getSignUserName())){
							ldTextview.setText(processIdea.getSignUserName());
						}
						
						LinearLayout sign_in_layout = (LinearLayout) view.findViewById(R.id.sign_in_layout);
						if(StringUtil.isNotEmpty(processIdea.getSignUserPath())){
							sign_in_layout.setVisibility(View.VISIBLE);
							final	ImageView signImageView = (ImageView) view.findViewById(R.id.sign_in_image_view);
							String url = processIdea.getSignUserPath();
							
							Bitmap bitmap = AsyncImageLoader.loadDrawable(url, new ImageCallback() {
								@Override
								public void imageLoaded(Bitmap imageDrawable, String imageUrl) {
//										ImageView imageView = (ImageView)listView.findViewWithTag(imageUrl);
										if(imageDrawable!=null ){
//											imageDrawable = ImageUtil.getRoundedCornerBitmap(imageUrl,imageDrawable, 10.0f);
//											imageView.setImageBitmap(imageDrawable);
											signImageView.setBackgroundDrawable(new BitmapDrawable(imageDrawable));
										}
								}
							});
						}
						
						process_idea_zhubanbumen_layout.addView(view);
						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.FILL_PARENT, 8);
						TextView textView = new TextView(this);
						textView.setLayoutParams(layoutParams);
						process_idea_zhubanbumen_layout.addView(textView);
						
					}
				}
			}
			document_path_layout.setFocusable(true);
			document_path_layout.requestFocus();
			document_path_layout.setFocusableInTouchMode(true);
			
		}
		
		//提交审批差公文
		if(arrayList.size()>0&&arrayList.get(0) instanceof SubmitBusinessTripBean){
			ToastUtil.showToast(getApplicationContext(), "您的签批已经成功");
			//跳转至前一页面
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), ToDoThingActivity.class);
			startActivity(intent);
			this.finish();
		}
			
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.confirm_btn://确定按钮
			if(StringUtil.isEmpty(shenpiyijian_edittext.getText().toString())){
				ToastUtil.showToast(getApplicationContext(), "请填写意见");
				shenpiyijian_edittext.setText(null);
				return ;
			}
			confirmToServer();
			break;
		
		default:
			break;
		}
	}
	
	void  confirmToServer(){
		String reqUrl =ConfigAttrs.BASE_URL+"SubmitDocumentResult.ashx";
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("userName", SharePreferencesUtil.getLastLoginAccount(getApplicationContext(), ConfigAttrs.LAST_LOGIN_ACCOUNT));
		hashMap.put("passWord", SharePreferencesUtil.getLastLoginAccount(getApplicationContext(), ConfigAttrs.LAST_LOGIN_PWD));
		if(StringUtil.isEmpty(deviceId)){
			deviceId = "0000000000";
		}
		hashMap.put("deviceId", deviceId);
		hashMap.put("InsID", documentBean.getInsID());
		hashMap.put("signComment", shenpiyijian_edittext.getText().toString());
		hashMap.put("JobStepID", String.valueOf(documentBean.getJobStepID()));

		ThreadManger.exeTask(this, ConfigAttrs.SUBMIT_BUSINESS_TRIP_TASK_FLAG, hashMap, reqUrl);
	}
	
	  /**
	 * 打开文件
	 * @param file
	 */ 
	private void openFile(File file){ 
	     
	    Intent intent = new Intent(); 
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
	    //设置intent的Action属性 
	    intent.setAction(Intent.ACTION_VIEW); 
	    //获取文件file的MIME类型 
	    String type = getMIMEType(file); 
	    //设置intent的data和Type属性。 
	    intent.setDataAndType(Uri.fromFile(file), type); 
	    //跳转 
	    startActivity(intent);   
	     
	} 
	 
	/**
	 * 根据文件后缀名获得对应的MIME类型。
	 * @param file
	 */ 
	private String getMIMEType(File file) { 
	     
	    String type="*/*"; 
	    String fName = file.getName(); 
	    //获取后缀名前的分隔符"."在fName中的位置。 
	    int dotIndex = fName.lastIndexOf("."); 
	    if(dotIndex < 0){ 
	        return type; 
	    } 
	    /* 获取文件的后缀名*/ 
	    String end=fName.substring(dotIndex,fName.length()).toLowerCase(); 
	    if(end=="")return type; 
	    //在MIME和文件类型的匹配表中找到对应的MIME类型。 
	    for(int i=0;i<MIME_MapTable.length;i++){ //MIME_MapTable??在这里你一定有疑问，这个MIME_MapTable是什么？ 
	        if(end.equals(MIME_MapTable[i][0])) 
	            type = MIME_MapTable[i][1]; 
	    }        
	    return type; 
	} 
	
	String [][] MIME_MapTable={ 
            //{后缀名，MIME类型} 
            {".3gp",    "video/3gpp"}, 
            {".apk",    "application/vnd.android.package-archive"}, 
            {".asf",    "video/x-ms-asf"}, 
            {".avi",    "video/x-msvideo"}, 
            {".bin",    "application/octet-stream"}, 
            {".bmp",    "image/bmp"}, 
            {".c",  "text/plain"}, 
            {".class",  "application/octet-stream"}, 
            {".conf",   "text/plain"}, 
            {".cpp",    "text/plain"}, 
            {".doc",    "application/msword"}, 
            {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, 
            {".xls",    "application/vnd.ms-excel"},  
            {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, 
            {".exe",    "application/octet-stream"}, 
            {".gif",    "image/gif"}, 
            {".gtar",   "application/x-gtar"}, 
            {".gz", "application/x-gzip"}, 
            {".h",  "text/plain"}, 
            {".htm",    "text/html"}, 
            {".html",   "text/html"}, 
            {".jar",    "application/java-archive"}, 
            {".java",   "text/plain"}, 
            {".jpeg",   "image/jpeg"}, 
            {".jpg",    "image/jpeg"}, 
            {".js", "application/x-javascript"}, 
            {".log",    "text/plain"}, 
            {".m3u",    "audio/x-mpegurl"}, 
            {".m4a",    "audio/mp4a-latm"}, 
            {".m4b",    "audio/mp4a-latm"}, 
            {".m4p",    "audio/mp4a-latm"}, 
            {".m4u",    "video/vnd.mpegurl"}, 
            {".m4v",    "video/x-m4v"},  
            {".mov",    "video/quicktime"}, 
            {".mp2",    "audio/x-mpeg"}, 
            {".mp3",    "audio/x-mpeg"}, 
            {".mp4",    "video/mp4"}, 
            {".mpc",    "application/vnd.mpohun.certificate"},        
            {".mpe",    "video/mpeg"},   
            {".mpeg",   "video/mpeg"},   
            {".mpg",    "video/mpeg"},   
            {".mpg4",   "video/mp4"},    
            {".mpga",   "audio/mpeg"}, 
            {".msg",    "application/vnd.ms-outlook"}, 
            {".ogg",    "audio/ogg"}, 
            {".pdf",    "application/pdf"}, 
            {".png",    "image/png"}, 
            {".pps",    "application/vnd.ms-powerpoint"}, 
            {".ppt",    "application/vnd.ms-powerpoint"}, 
            {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, 
            {".prop",   "text/plain"}, 
            {".rc", "text/plain"}, 
            {".rmvb",   "audio/x-pn-realaudio"}, 
            {".rtf",    "application/rtf"}, 
            {".sh", "text/plain"}, 
            {".tar",    "application/x-tar"},    
            {".tgz",    "application/x-compressed"},  
            {".txt",    "text/plain"}, 
            {".wav",    "audio/x-wav"}, 
            {".wma",    "audio/x-ms-wma"}, 
            {".wmv",    "audio/x-ms-wmv"}, 
            {".wps",    "application/vnd.ms-works"}, 
            {".xml",    "text/plain"}, 
            {".z",  "application/x-compress"}, 
            {".zip",    "application/x-zip-compressed"}, 
            {"",        "*/*"}   
        }; 

	boolean isExist(String path){
		File file = new File(path);
		if(file.exists()){
			return true;
		}
		
		return false;
	}
	
	Handler  mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(dialog!=null&&dialog.isShowing()) dialog.dismiss();
			switch (msg.what) {
			case 0://文件下载成功
				ToastUtil.showToast(mContext, "下载文件成功！！！");
				//直接
				if(file!=null&&file.exists()){
					openFile(file);
				}
				break;
			case 1://文件下载失败
				ToastUtil.showToast(mContext, "下载文件失败！！！");
				break;
			default:
				break;
			}
			
		};
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			//跳转至前一页面
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), DocumentManagementActivity.class);
			startActivity(intent);
			this.finish();
			return false;
		}
		return true;
	}

}
